package cn.bugstack.openai.session.defaults;

import cn.bugstack.openai.executor.Executor;
import cn.bugstack.openai.executor.parameter.RequestChannel;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.OpenAiSessionFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 会话工厂实现
 *
 * @author 小傅哥，微信：fustack
 */
@Slf4j
public class DefaultOpenAiSessionFactory implements OpenAiSessionFactory {

    private final Configuration configuration;

    @Getter
    @Setter
    private Interceptor interceptor;


    public DefaultOpenAiSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public OpenAiSession openSession() {
        // 1. 日志配置
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(configuration.getLevel());
        // 2. 开启 Http 客户端
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .proxySelector(new SwitchProxySelector())
                .connectTimeout(configuration.getConnectTimeout(), TimeUnit.SECONDS)
                .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS)
                .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS);
        if (getInterceptor() != null) {
            builder.addInterceptor(getInterceptor());
            builder.proxySelector(new SwitchProxySelector());
        }
        configuration.setOkHttpClient(builder.build());
        // 3. 创建执行器【模型 -> 映射执行器】
        Map<RequestChannel, Executor> executorGroup = configuration.newExecutorGroup();
        // 4. 创建会话服务
        return new DefaultOpenAiSession(configuration, executorGroup);
    }
}
